package com.example.unique.ui.person

import android.app.Activity.RESULT_OK
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import com.example.unique.EditProfileActivity
import com.example.unique.database.DatabaseHelper
import com.example.unique.databinding.PersonBinding
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


class PersonFragment : Fragment() {
    private var _binding: PersonBinding? = null
    private val binding get() = _binding!!
    private lateinit var personViewModel: PersonViewModel
    private lateinit var sno:String
    private lateinit var userDatabase:DatabaseHelper
    private lateinit var avatarUri: Uri
    private lateinit var imageUri: Uri

    // 启动图库选择器
    private val imagePickerLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
        uri?.let {
            binding.avatarImageView.setImageURI(it)
            avatarUri = it // 更新头像 URI
            personViewModel.setAvatarUri(it.toString())
        }
    }

    // 启动相机拍照
    private val takePictureLauncher = registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccess ->
        if (isSuccess) {
            binding.avatarImageView.setImageURI(imageUri)
            avatarUri = imageUri // 更新头像 URI
            personViewModel.setAvatarUri(imageUri.toString())
        }else{
            Log.e("PersonFragment", "无法启动相机应用")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 从 Activity 获取社团信息
        sno = activity?.intent?.getStringExtra("sno").orEmpty()
        // 初始化数据库实例
        userDatabase=DatabaseHelper(requireContext())
        // ViewModel 初始化
        personViewModel= PersonViewModel(userDatabase)

        // 获取用户信息
        personViewModel.getUserBySno(sno)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // 绑定布局
        _binding = PersonBinding.inflate(inflater, container, false)
        imageUri = Uri.fromFile(File.createTempFile("avatar_", ".jpg", requireContext().cacheDir))
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupObservers() // 设置观察者
        fetchUserDetails() // 加载用户信息
        setupClickListeners() // 设置点击事件
    }

    private fun setupObservers() {
        // 观察用户数据变化
        personViewModel.userData.observe(viewLifecycleOwner) { user ->
            if (user != null) {
                // 更新 UI，动态替换用户名
                binding.tvUserName.text = "欢迎您，${user.name}"  // 将用户姓名替换到TextView中
            } else {
                // 如果没有找到用户信息，可以设置默认文本
                binding.tvUserName.text = "欢迎您，用户XXX"
            }
        }

        // 观察头像路径变化
        personViewModel.avatarUri.observe(viewLifecycleOwner) { uri ->
            uri?.let {
                binding.avatarImageView.setImageURI(Uri.parse(it)) // 更新头像
            }
        }
    }
    // 弹出选择头像来源的对话框
    private fun showAvatarSelectionDialog() {
        val options = arrayOf("从相册选择", "使用相机拍照")
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("选择头像来源")
            .setItems(options) { dialog, which ->
                when (which) {
                    0 -> imagePickerLauncher.launch("image/*") // 启动图库选择器
                    1 -> takePictureLauncher.launch(imageUri) // 启动相机拍照
//                    1 -> dispatchTakePictureIntent()
                }
            }
            .show()
    }
//    private fun dispatchTakePictureIntent() {
//        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//        if (takePictureIntent.resolveActivity(requireContext().packageManager) != null) {
//            // 创建文件并获取 URI
//            val photoFile: File? = createImageFile()
//            photoFile?.also {
//                // 使用 FileProvider 获取 URI
//                imageUri = FileProvider.getUriForFile(
//                    requireContext(),
//                    "${requireContext().packageName}.fileprovider", it
//                )
//                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
//
//                // 启动相机应用
//                takePictureLauncher.launch(imageUri) // 使用 FileProvider 提供的 URI 启动相机
//            }
//        }
//    }
//    private fun createImageFile(): File? {
//        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
//        val storageDir: File? = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
//        return try {
//            File.createTempFile("JPEG_${timeStamp}_", ".jpg", storageDir)
//        } catch (ex: Exception) {
//            ex.printStackTrace()
//            null
//        }
//    }
    private fun setupClickListeners() {
        // 编辑资料
        binding.editProfileButton.setOnClickListener {
            // 获取用户信息
            val user = personViewModel.userData.value
            val avatarUri = personViewModel.avatarUri.value
            // 创建 Intent 跳转到 EditProfileActivity
            val intent = Intent(requireContext(), EditProfileActivity::class.java)
            // 传递用户数据（姓名、学号、学院等）
            user?.let {
                intent.putExtra("user_name", it.name)
                intent.putExtra("user_academy", it.academy)
                intent.putExtra("user_club", it.club)
                intent.putExtra("user_password", it.password)
            }
            // 启动 EditProfileActivity
            startActivityForResult(intent, EDIT_PROFILE_REQUEST)
        }

        // 修改头像
        binding.avatarImageView.setOnClickListener {
            showAvatarSelectionDialog()
        }

        // 退出程序
        binding.logoutButton.setOnClickListener {
            showLogoutConfirmation()
        }
    }

    private fun showLogoutConfirmation() {
        AlertDialog.Builder(requireContext())
            .setTitle("退出程序")
            .setMessage("确定要退出吗？")
            .setPositiveButton("确定") { _, _ ->
                requireActivity().finish() // 退出当前 Activity
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun fetchUserDetails() {
        // 获取并显示用户详情
        personViewModel.getUserBySno(sno)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == EDIT_PROFILE_REQUEST && resultCode == RESULT_OK) {
            // 获取返回的用户信息和头像 URI
            val updatedName = data?.getStringExtra("updated_name")
            val updatedAcademy = data?.getStringExtra("updated_academy")
            val updatedClub = data?.getStringExtra("updated_club")
            val updatePassword =data?.getStringExtra("updated_password")

            // 更新 ViewModel 中的数据
            updatedName?.let { personViewModel.userData.value?.name = it }
            updatedAcademy?.let { personViewModel.userData.value?.academy = it }
            updatedClub?.let { personViewModel.userData.value?.club = it }
            updatePassword?.let { personViewModel.userData.value?.password = it }

            userDatabase.updateAll(sno,updatedAcademy,updatedClub,updatePassword)
            // 重新加载用户数据
            personViewModel.getUserBySno(sno)
        }
    }


    companion object {
        private const val EDIT_PROFILE_REQUEST = 1001
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null // 清理绑定的视图
    }
}

